package com.lone.design.pattern.creational.singleton.demo4;

import java.io.*;

/**
 * @author Lone
 * @date 2021/9/24 9:53 周五
 * 破坏单例模式：
 * 单例类（Singleton）可以创建多个对象，枚举方式除外。有两种方式，分别是序列化和反射。
 */
public class SerializableTest {
    public static void main(String[] args) throws Exception {
//        writeObject2File();
         // 单例从文件反序列化后被破坏
         // 解决方法 在单例中定义readResolve
         Singleton instance1 = readObjectFromFile();
         Singleton instance2 = readObjectFromFile();

         System.out.println(instance1 == instance2);
    }

    public static Singleton readObjectFromFile() throws Exception {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./a.txt"));
        //第一个读取Singleton对象
        Singleton instance = (Singleton) ois.readObject();
        ois.close();
        return instance;
    }

    public static void writeObject2File() throws Exception {
        Singleton instance = Singleton.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./a.txt"));
        oos.writeObject(instance);
        oos.close();
    }
}
